package com.xuanwei.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuanwei.core.exception.XwException;
import com.xuanwei.core.service.IXwHotWordService;
import com.xuanwei.dao.entity.XwHotWord;
import com.xuanwei.dao.mapper.XwHotWordMapper;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author mjy
 * @since 2019-08-07
 */
@Service
public class XwHotWordServiceImpl extends ServiceImpl<XwHotWordMapper, XwHotWord> implements IXwHotWordService {


    @Override
    public void add(Integer id, String word, Integer orderBy) {
        if (id == null) {
            if (findByName(word) != null) {
                throw new XwException("已存在相同词汇");
            }
            XwHotWord hotWord = new XwHotWord();
            hotWord.setWord(word);
            hotWord.setOrderBy(orderBy);
            hotWord.setUpdateTime(LocalDateTime.now());
            hotWord.setCreateTime(LocalDateTime.now());
            save(hotWord);
        } else {
            XwHotWord one = getOne(new QueryWrapper<XwHotWord>().select("id").eq("id", id));
            if (one == null) {
                throw new XwException("数据不存在");
            }

            XwHotWord byName = findByName(word);
            if (byName != null && byName.getId() != id) {
                throw new XwException("已存在相同词汇");
            }
            one.setUpdateTime(LocalDateTime.now());
            one.setOrderBy(orderBy);
            one.setWord(word);
            updateById(one);
        }
    }

    private XwHotWord findByName(String name) {
        return getOne(new QueryWrapper<XwHotWord>().select("id").eq("word", name));
    }

    @Override
    public List<XwHotWord> findAll() {
        return list(new QueryWrapper<XwHotWord>().orderByAsc("order_by"));
    }

    @Override
    public void del(Integer id) {
     baseMapper.deleteById(id);
    }
}
